package Campus.help.task.config;

import Campus.help.common.utils.R;
import Campus.help.task.dao.OrderEvaluationInfoMapper;
import Campus.help.task.dao.TaskInfoMapper;
import Campus.help.task.entity.OrderEvaluationInfo;
import Campus.help.task.fegin.UserOpenFeginService;
import Campus.help.task.service.AdvertisementInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
@Slf4j
public class MultithreadScheduleTask {

    private static final Map<Long, BigDecimal> map = new HashMap<>();
    private static final Map<Long, Integer> map1 = new HashMap<>();
    @Autowired
    private TaskInfoMapper taskInfoMapper;

    @Autowired
    private OrderEvaluationInfoMapper evaluationInfoMapper;

    @Autowired
    private AdvertisementInfoService advertisementInfoService;

    @Autowired
    private UserOpenFeginService userOpenFeginService;

    @Async
    @Scheduled(cron = "0 0/3 * * * ?") //每分钟
    public void MonitoringUnpaidOrder() throws InterruptedException {
        log.info("监听订单状态");
        taskInfoMapper.OrderMonitoring(LocalDateTime.now());
    }

    @Async
    @Scheduled(cron = "0 0/2 * * * ?") //2分钟
    public void Calculate_Ratings() {
        map.clear();
        map1.clear();
       List<OrderEvaluationInfo> list = evaluationInfoMapper.getEvaluaInfos(LocalDateTime.now());
       long userId = 0l;
       for (OrderEvaluationInfo info : list){
           userId = info.getReceiverId();
           BigDecimal receiverRating = info.getReceiverRating();
           if (map.containsKey(userId)){
               map.put(userId,map.get(userId).add(receiverRating));
               map1.put(userId,map1.get(userId)+1);
           }else {
               map.put(userId,receiverRating);
               map1.put(userId,1);
           }
       }
        Set<Long> keySet = map.keySet();
       for (long id : keySet){
           R r = userOpenFeginService.updateRate(id, map.get(id).divide(new BigDecimal(map1.get(userId))));
           if (r.getCode()==400)
               log.info("计算失败，0用户为："+id);
       }
        log.info("重新计算评分");
    }

    @Async
    @Scheduled(cron = "0 0/3 * * * ?") //每分钟
    public void Monitoringadvertisement() throws InterruptedException {
        log.info("监听订单状态");
        R r = advertisementInfoService.del(LocalDateTime.now());
    }
}